<template>
	<SubBread></SubBread>
	<SubFilter @filter-change="changeFilter"></SubFilter>
	<div class="goods-list">
		<SubSort @sort-change="changeSort"></SubSort>
		<ul>
			<li v-for="item in goodsList" :key="item.id">
				<GoodsItem :goods="item"></GoodsItem>
			</li>
		</ul>
		<XtxInfiniteLoading :loading="loading" :finished="finished" @infinite="getData" />
	</div>
</template>

<script>
	import SubBread from './components/sub-bread'
	import SubFilter from './components/sub-filter'
	import SubSort from './components/sub-sort'
	import GoodsItem from './components/goods-item'

	import {
		ref,
		watch
	} from 'vue'
	import {
		findSubCategoryGoods
	} from '@/api/category'
	import {
		useRoute
	} from 'vue-router'

	export default {
		components: {
			SubBread,
			SubFilter,
			SubSort,
			GoodsItem
		},

		setup() {
			const route = useRoute()
			const loading = ref(false)
			const finished = ref(false)
			const goodsList = ref([])

			let reqParams = {
				page: 1,
				pageSize: 20
			}

			const getData = () => {
				loading.value = true
				reqParams.categoryId = route.params.id
				findSubCategoryGoods(reqParams).then(({
					result
				}) => {
					if (result.items.length) {
						goodsList.value.push(...result.items)
						reqParams.page++
					} else {
						finished.value = true
					}
					loading.value = false
				})
			}

			watch(() => route.params.id, newVal => {
				if (newVal && `/category/sub/${newVal}` === route.path) {
					goodsList.value = []
					reqParams = {
						page: 1,
						pageSize: 20
					}
					finished.value = false
				}
			})

			const changeFilter = filterParams => {
				finished.value = false
				reqParams = {
					...reqParams,
					...filterParams
				}
				reqParams.page = 1
				goodsList.value = []
			}

			const changeSort = sortParams => {
				finished.value = false
				reqParams = {
					...reqParams,
					...sortParams
				}
				reqParams.page = 1
				goodsList.value = []
				getData()
			}

			return {
				loading,
				finished,
				goodsList,
				getData,
				changeFilter,
				changeSort
			}
		}
	}
</script>

<style lang="less" scoped>
	.goods-list {
		background: #fff;
		padding: 0 25px;
		margin-top: 25px;

		ul {
			display: flex;
			flex-wrap: wrap;
			padding: 0 5px;

			li {
				margin-right: 20px;
				margin-bottom: 20px;

				&:nth-child(5n) {
					margin-right: 0;
				}
			}
		}
	}
</style>
